var Common = require('utils/common');
var api = require('api');
var T;
const url = api.url;

App({
  checkNull: function (value) {
    let val = (value || '').trim();
    if (val == '' || val == null) {
      return true;
    } else {
      return false;
    }
  },
  checkPhone: function (phone) {
    var model = /^1(3|4|5|6|7|8|9)\d{9}$/;
    if (model.test(phone)) {
      return false;
    } else {
      return true;
    }
  },
  globalData: {
    domain: url,
    isLogin: false,
    userInfo: null,
    code:"",
  },
  onLaunch: function () {
    wx.getSystemInfo({
      success: (res) => {
        this.SystemInfo = res;
      }
    })


    // 展示本地存储能力
    // var logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })

    
  },
  getUserInfo: function (cb) {
    var that = this
    if (this.globalData.userInfo) {
      // typeof cb == "function" && cb(this.globalData.isLogin)
      login(that, cb);
    } else {
      login(that, cb);

    }
  },



  // ---------------------------
  init: function (ts) {
    // console.log("%c>>>函数初始化", 'color:#ff0000')
    T = ts;
  },

  /* 公共函数---------------------------------------- */
  setdata: function (e) {
    var obj = {};
    console.log(e.currentTarget.dataset.key, e.currentTarget.dataset.val)
    obj[e.currentTarget.dataset.key] = e.currentTarget.dataset.val;
    T.setData(obj);
  },
  setdatas: function (e) {
    var obj = {};
    var key = e.currentTarget.dataset.key.split(",");
    var val = e.currentTarget.dataset.val.split(",");
    for (var i = 0; i < key.length; i++) {
      obj[key[i]] = val[i];
    }
    T.setData(obj);
  },
  input: function (e) {
    var obj = {};
    obj[e.currentTarget.dataset.name] = e.detail.value;
    T.setData(obj);

    console.log(obj)
  },

  upload_img: function (e) {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          url: url+'/clientPublic/upRepairImg',
          filePath: tempFilePaths[0],
          name: 'img',
          success: (res) => {
            console.log(res.data.toString())
            var data = JSON.parse(res.data);
            console.log(data)
            var obj = {};
            obj[e.currentTarget.dataset.name] = data.data[0];
            T.setData(obj);

          }
        })

      }
    })
  },

  goto: function (e) {
    console.log(e.currentTarget.dataset.url);
    wx.navigateTo({
      url: e.currentTarget.dataset.url
    })
  },

  closeto: function (e) {
    console.log(e.currentTarget.dataset.url);
    wx.redirectTo({
      url: e.currentTarget.dataset.url
    })
  },


  history_back: function () {
    wx.navigateBack({
      delta: -1
    })
  },

  preview_image: function (e) {
    console.log(e.currentTarget.dataset.url)
    wx.previewImage({
      urls: [e.currentTarget.dataset.url]
    });
  },

  phone: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.val
    })
  },

  toast: function (str) {
    wx.showToast({
      title: str,
      icon: 'none'
    })
  },

  // ----------------------------------------------------------
  api:api,

  SystemInfo:{},

  // 工具类
  tool: {
    ymd: function () {
      var myDate = new Date();
      let y = myDate.getFullYear();
      let m = myDate.getMonth() + 1;
      let d = myDate.getDate();

      return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
    },
    ymdhis: function () {
      var myDate = new Date();

      // myDate.getYear(); //获取当前年份(2位)
      // myDate.getFullYear(); //获取完整的年份(4位,1970-????)
      // myDate.getMonth(); //获取当前月份(0-11,0代表1月)
      // myDate.getDate(); //获取当前日(1-31)
      // myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
      // myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
      // myDate.getHours(); //获取当前小时数(0-23)
      // myDate.getMinutes(); //获取当前分钟数(0-59)
      // myDate.getSeconds(); //获取当前秒数(0-59)
      // myDate.getMilliseconds(); //获取当前毫秒数(0-999)

      return myDate.getFullYear() + "-"
        + (myDate.getMonth() + 1) + "-"
        + (myDate.getDate()) + "-"
        + (myDate.getHours()) + "-"
        + (myDate.getMinutes()) + "-"
        + (myDate.getSeconds())
    },

    ymdtimestamp: function () {
      var now = new Date();
      var yy = now.getFullYear();      //年
      var mm = now.getMonth() + 1;     //月
      var dd = now.getDate();          //日

      var clock = yy + "-";
      if (mm < 10) clock += "0";
      clock += mm + "-";
      if (dd < 10) clock += "0";
      clock += dd + " ";
      return new Date(clock + '00:00:00').getTime() / 1000;
    },

    timestampToTime: function (timestamp) {
      var date = new Date(timestamp * 1000);
      var Y = date.getFullYear();
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
      var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
      var h = date.getHours();
      var m = date.getMinutes();
      var s = date.getSeconds();

      return Y + "-" + M + "-" + D;
    }


  }







})
































//调用登录接口
function login(that, cb) {
  console.log("调用登陆接口")
  var url = getApp().globalData.domain;
  console.log("domain",url);
  new Promise(function (resolve) {
    // 显示加载中
    wx.showToast({
      title: "正在登录...",
      icon: 'loading'
    });
    wx.login({
      success: function (res) {
        resolve(res);
      }
    });
  }).then(function (xdata) {
    console.log(xdata)
    return new Promise(function (resolve, reject) {
      console.log("进来了")
      wx.request({
        url: url + '/clientPublic/login',
        data: {
          code: xdata.code
        },
        method: "POST",
        dataType: 'json',
        header: {
          "Content-Type": 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          var data = res.data;
          console.log("登陆:", res)
          wx.setStorageSync("token", res.data.data);

          set_client_user_info();

          //判断是否已经绑定过手机
          if (data.data.phone){
            wx.setStorageSync("isBindPhoneFlag", true);
          }
          that.globalData.isLogin = true
          resolve(res);
          
        },
        fail: function (res) {
          Common.showToastForJson(res);
        },
        complete(res) {
          console.log(res)
        }
      })
    });
  }).then(function (xdata) {
    console.log('sssss', xdata);
    //授权成功后，跳转进入小程序首页
    wx.switchTab({
      url: '/pages/index/index'
    })
    return new Promise(function (resolve, reject) {
      wx.getUserInfo({
        success: function (res) {
          console.log('userInfo', res)
          that.globalData.userInfo = res.userInfo
          resolve(res);
        },
        fail: function (res) {
          // 取消授权
          reject(res);
        }
      })
    });
  }).then(function (xdata) {
    
  }, function (xdata) {
    wx.hideToast();
    wx.showModal({
      title: '提示',
      content: "您取消了授权",
      success: function (res) {
        console.log(res)
        wx.setStorageSync("isShow", true);

        wx.navigateTo({
          url: '/pages/login/login'
        })

        if (res.confirm) {
          console.log('用户点击确定')
        }
      }
    });
  }).then(function (xdata) {
    wx.hideToast();
    // cb(that.globalData.userInfo);
  }, function (xdata) {
    wx.hideToast();
    wx.showModal({
      title: '提示',
      content: xdata.errmsg,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        }
      }
    });
  });
}


function set_client_user_info(){
  wx.getUserInfo({
    success: function (res) {
      console.log(res);
      var UserInfo = res.rawData
      var encryptedData = res.encryptedData;
      var iv = res.iv;
      api.clientPublic_info({
        token: wx.getStorageSync("token"),
        encryptedData: encryptedData,
        iv: iv
      }, (res) => {
        wx.setStorageSync("token",res.data.token)
        console.log("--------------------设置token-----------------------", res.data.token);
      })
    }
  })
}